package com.lzc.jobrecomendbackend.service.skills.impl;

import com.lzc.jobrecomendbackend.model.Job;
import com.lzc.jobrecomendbackend.model.skills.*;
import com.lzc.jobrecomendbackend.repository.JobRepository;
import com.lzc.jobrecomendbackend.service.skills.SkillService;
import com.lzc.jobrecomendbackend.utils.SkillExtractor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SkillServiceImpl implements SkillService {

    @Autowired
    private JobRepository jobRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public SkillDistributionVO getSkillDistribution(String city, String education, String experience, int page, int size) {
        // 构建查询条件
        Query query = buildQuery(city, education, experience);
        
        // 查询符合条件的职位
        List<Job> jobs = mongoTemplate.find(query, Job.class);
        
        // 提取技能并统计
        Map<String, Integer> skillCountMap = new HashMap<>();
        for (Job job : jobs) {
            List<String> skills = SkillExtractor.extractSkills(job.get职位名字());
            for (String skill : skills) {
                skillCountMap.put(skill, skillCountMap.getOrDefault(skill, 0) + 1);
            }
        }
        
        // 计算总技能数
        int totalSkills = skillCountMap.size();
        
        // 排序并分页
        List<Map.Entry<String, Integer>> sortedSkills = skillCountMap.entrySet().stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                .collect(Collectors.toList());
        
        // 计算分页
        int startIndex = (page - 1) * size;
        int endIndex = Math.min(startIndex + size, sortedSkills.size());
        
        // 防止索引越界
        if (startIndex >= sortedSkills.size()) {
            return new SkillDistributionVO(Collections.emptyList(), totalSkills, page, size);
        }
        
        List<SkillItem> skillItems = new ArrayList<>();
        for (int i = startIndex; i < endIndex; i++) {
            Map.Entry<String, Integer> entry = sortedSkills.get(i);
            String skill = entry.getKey();
            int count = entry.getValue();
            double percentage = (double) count / jobs.size() * 100;
            skillItems.add(new SkillItem(skill, count, percentage));
        }
        
        return new SkillDistributionVO(skillItems, totalSkills, page, size);
    }

    @Override
    public SkillCombinationVO getSkillCombinations(String city, String experience, int page, int size) {
        // 构建查询条件
        Query query = buildQuery(city, null, experience);
        
        // 查询符合条件的职位
        List<Job> jobs = mongoTemplate.find(query, Job.class);
        
        // 提取职位名称
        List<String> jobTitles = jobs.stream()
                .map(Job::get职位名字)
                .collect(Collectors.toList());
        
        // 提取技能组合
        List<Set<String>> skillCombinations = SkillExtractor.extractSkillCombinations(jobTitles);
        
        // 统计组合出现次数
        Map<String, Integer> combinationCountMap = new HashMap<>();
        Map<String, List<String>> combinationSkillsMap = new HashMap<>();
        
        for (Set<String> combination : skillCombinations) {
            if (combination.size() < 2) continue;
            
            List<String> sortedSkills = new ArrayList<>(combination);
            Collections.sort(sortedSkills);
            String combinationKey = String.join("+", sortedSkills);
            
            combinationCountMap.put(combinationKey, combinationCountMap.getOrDefault(combinationKey, 0) + 1);
            combinationSkillsMap.putIfAbsent(combinationKey, sortedSkills);
        }
        
        // 计算总组合数
        int totalCombinations = combinationCountMap.size();
        
        // 排序并分页
        List<Map.Entry<String, Integer>> sortedCombinations = combinationCountMap.entrySet().stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                .collect(Collectors.toList());
        
        // 计算分页
        int startIndex = (page - 1) * size;
        int endIndex = Math.min(startIndex + size, sortedCombinations.size());
        
        // 防止索引越界
        if (startIndex >= sortedCombinations.size()) {
            return new SkillCombinationVO(Collections.emptyList(), totalCombinations, page, size);
        }
        
        List<SkillCombinationItem> combinationItems = new ArrayList<>();
        for (int i = startIndex; i < endIndex; i++) {
            Map.Entry<String, Integer> entry = sortedCombinations.get(i);
            String combination = entry.getKey();
            int count = entry.getValue();
            double percentage = (double) count / skillCombinations.size() * 100;
            List<String> skills = combinationSkillsMap.get(combination);
            
            combinationItems.add(new SkillCombinationItem(combination, skills, count, percentage));
        }
        
        return new SkillCombinationVO(combinationItems, totalCombinations, page, size);
    }
    
    /**
     * 构建查询条件
     */
    private Query buildQuery(String city, String education, String experience) {
        Query query = new Query();
        
        // 添加筛选条件
        if (city != null && !city.isEmpty()) {
            query.addCriteria(Criteria.where("工作城市").is(city));
        }
        
        if (education != null && !education.isEmpty()) {
            query.addCriteria(Criteria.where("学历要求").is(education));
        }
        
        if (experience != null && !experience.isEmpty()) {
            query.addCriteria(Criteria.where("经验要求").is(experience));
        }
        
        return query;
    }
} 